package com.mo.admin.security.filters;

import com.alibaba.fastjson2.JSON;
import com.mo.admin.api.user.domain.User;
import com.mo.admin.api.user.service.UserService;
import com.mo.admin.common.Result;
import com.mo.admin.security.domain.UserDetailsImpl;
import com.mo.admin.security.utils.JWTUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

/**
 * 校验Header中的token
 */
@Component
public class JwtOncePerRequestFilter extends OncePerRequestFilter {
    @Resource
    private JWTUtils jwtUtils;

    @Resource
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        // 访问 /login 接口放行
        if (!StringUtils.hasLength(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        String userId = null;
        try {
            if (jwtUtils.validateToken(token)) {
                userId = jwtUtils.getSubject(token);
            }
        } catch (Exception e) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(Result.error("token有误，请重新登录", HttpServletResponse.SC_BAD_REQUEST)));
            return;
        }

        // 重新查找用户信息，并设置到 SecurityContextHolder 中，自己写一个方法来查询，因为需要查询权限列表
        // 重新创建权限列表
        // String[] auths = {"sys:add", "sys:delete", "sys:edit", "sys:get", "ROLE_ADMIN"};
        // List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(auths);

        User user = userService.getById(userId);
        UserDetailsImpl loginUser = new UserDetailsImpl(user);

        //List<GrantedAuthority> authorities = user.getAuthorities();
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList();
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, authorities);
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request, response);
    }
}